package android.example.imageandanimation;

import android.content.Context;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.graphics.Paint;
import android.graphics.Color;
import android.graphics.Canvas;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.content.res.AssetManager;
import java.io.InputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.Matrix;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageAndAnimationView extends SurfaceView implements SurfaceHolder.Callback, Runnable{
	private Paint paint;
	private AssetManager assetManager;
	private InputStream inputStream;
	private Bitmap backround_bitmap;
	private Bitmap transparent_background_image, tmp_bitmap;
	private int screen_width, screen_height;
	
		//holder
	private SurfaceHolder o_surfaceholder;
	//main game thread
	private Thread o_game_mainthread;
	private boolean i_thread_can_run = false;
	
	private Animation ryu_animation;
	private Bitmap ryu_anim_bitmap;
	private double frame_counter = 0;
	
	public ImageAndAnimationView(Context context){
		super(context);
		
		o_surfaceholder = getHolder();
		o_surfaceholder.addCallback(this);
		paint = new Paint();
		screen_width = context.getResources().getDisplayMetrics().widthPixels;
		screen_height = context.getResources().getDisplayMetrics().heightPixels;
		assetManager = context.getAssets();//must put resource in assets/ folder
	}
	
	private Bitmap makeTransparent(Bitmap tmpImage)
	{
		int h = tmpImage.getHeight();
		int w = tmpImage.getWidth();
 
		Bitmap resultImage = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
 
		// assume the upperleft corner of the original image is a transparent pixel
		int transparentColor = tmpImage.getPixel(0,0);  
		for (int y=0;y<h;y++)
			for (int x=0;x<w;x++)
			{
				int color=tmpImage.getPixel(x,y);
				if(color==transparentColor)
					color=color & 0x00FFFFFF; // clear the alpha flag
				resultImage.setPixel(x,y,color);
			} 
		return resultImage;
	}
	
	@Override
    protected void onDraw(Canvas canvas){				
		//draw background fill with device screen size
		if(backround_bitmap != null)
			canvas.drawBitmap(backround_bitmap, new Rect(0, 0, backround_bitmap.getWidth(), backround_bitmap.getHeight()), new Rect(0, 0, screen_width, screen_height), paint);
		
		//draw transparent image
		if(transparent_background_image != null)
		canvas.drawBitmap(transparent_background_image, new Rect(0, 0, transparent_background_image.getWidth(), transparent_background_image.getHeight()), new Rect(0, 0, screen_width, transparent_background_image.getHeight()), paint);
		//set matrix and draw flip horizontal image
		Matrix matrix = new Matrix();
        matrix.setTranslate(transparent_background_image.getWidth(), transparent_background_image.getHeight() + 10);        
		matrix.preScale(-1f, 1f);
		if(transparent_background_image != null)
			canvas.drawBitmap(transparent_background_image, matrix, null);
		//set matrix and draw flip vertical image		
		matrix.setTranslate(0, 3*transparent_background_image.getHeight() + 20);
		matrix.preScale(1f, -1f);
		if(transparent_background_image != null)
			canvas.drawBitmap(transparent_background_image, matrix, null);		
		ryu_animation.render(canvas, screen_width/2, 3*transparent_background_image.getHeight() + 20);
		paint.setColor(Color.RED);		
		canvas.drawText("Frame: " + frame_counter, 5, 15, paint);
		frame_counter ++;
		
	}
	
	private void Initalize(){
		try { 
			//for background
			inputStream = assetManager.open("background.jpg");//must put resource in assets/ folder
			// inputStream = this.getResources().openRawResource(R.drawable.background);//put resource in res/ folder			
			backround_bitmap = BitmapFactory.decodeStream(inputStream);	
			
			//for transparent image			
			inputStream = assetManager.open("ryu_anim.png");//must put resource in assets/ folder
			// inputStream = this.getResources().openRawResource(R.drawable.ryu_anim);//put resource in res/ folder			
			tmp_bitmap = BitmapFactory.decodeStream(inputStream);
			transparent_background_image = makeTransparent(tmp_bitmap);			
			ryu_anim_bitmap = makeTransparent(tmp_bitmap);	
			inputStream.close();			
			ryu_animation = new Animation(ryu_anim_bitmap, 0, 0, 12, 60, 68);			
		} catch (IOException e) { 
			 // silently ignored, bad coder monkey, baaad! 
		} finally { 
			 // we should really close our input streams here. 
		}
		//game main thread
		o_game_mainthread = new Thread(this);
		o_game_mainthread.start();
		i_thread_can_run = true;
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Initalize();
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}
	
	@Override
	public void surfaceDestroyed(SurfaceHolder holder){
		boolean retry = true;
		i_thread_can_run = false;
        do {
            try {
                o_game_mainthread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);
		
	}
	
	@Override
	public void run(){
		while(i_thread_can_run){
			try{
				// Thread.sleep(20);
			}catch(Exception e){}			
			Canvas o_lockcanvas = o_surfaceholder.lockCanvas(null);
			synchronized (o_surfaceholder) {
				if(o_lockcanvas != null){
					onDraw(o_lockcanvas);
					o_surfaceholder.unlockCanvasAndPost(o_lockcanvas);
				}
			}
		}
	}
}